package com.yanwq.sayhi.controller.user.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.yanwq.sayhi.MainActivity;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.LocMgr;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.CacheConstant;
import com.yanwq.sayhi.common.constant.RegexConstant;
import com.yanwq.sayhi.common.event.UserEvent;
import com.yanwq.sayhi.common.tool.AppTool;
import com.yanwq.sayhi.common.tool.CropTool;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.User;
import com.yanwq.sayhi.widget.MEditText;
import com.yanwq.sayhi.widget.MToast;

import java.io.File;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class RegisterInfoActivity extends BaseToolbarActivity {

    @BindView(R.id.register_avatar)
    ImageView mAvatarV;
    @BindView(R.id.register_nickname)
    MEditText mNicknameV;
    @BindView(R.id.register_motto)
    MEditText mMottoV;
    @BindView(R.id.register_loc)
    TextView mLocV;

    @OnClick(R.id.register_avatar)
    void cropImage() {
        mCropTool.pick(this);
    }

    private File mPhotoFile;
    private String mFileName;
    private boolean hasAvatar;
    private JSONObject mAvatar;
    private CropTool mCropTool;

    private double mLon;
    private double mLat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_info);
        EventBus.getDefault().register(this);
    }

    @Override
    public void init() {
        mFileName = CacheConstant.getRandomFileName();
        mPhotoFile = new File(CacheConstant.getPhotoPath(), mFileName);
        mCropTool = new CropTool();
    }

    @Override
    public void initView() {
        mToolbar.setTitle("注册");

        LocMgr.getInstance(getApplicationContext()).locOne(new LocMgr.MLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                mLocV.setText(location.getLocationDescribe());
                mLon = location.getLongitude();
                mLat = location.getLatitude();
            }

            @Override
            public void onFail() {
                mLocV.setText("你确定自己在地球村？");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressWarnings("unused")
    public void onEvent(UserEvent event) {
        switch (event.getEventType()) {
            case UserEvent.LOGIN:
                finish();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        send();
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCropTool.crop(mPhotoFile, this, requestCode, resultCode, data, new CropTool.CropCallback() {
            @Override
            public void onComplete(Uri resultUri) {
                mAvatarV.setImageURI(resultUri);
                hasAvatar = true;
            }
        });
    }

    private void send() {
        if (!hasAvatar) {
            MToast.showShort(RegisterInfoActivity.this, "请选择头像");
            return;
        }

        if (!Pattern.matches(RegexConstant.motto, mMottoV.getText().toString())) {
            MToast.showShort(RegisterInfoActivity.this, "请填写签名");
            return;
        }

        if (!Pattern.matches(RegexConstant.nickname, mNicknameV.getText().toString())) {
            MToast.showShort(RegisterInfoActivity.this, "请填写昵称");
            return;
        }

        if (mAvatar == null) {
            uploadAvatar();
        } else {
            register();
        }
    }

    private void uploadAvatar() {
        OkRequestParams params = new OkRequestParams();

        params.put("mf", mFileName, mPhotoFile);

        OkRestClient.getInstance().post(this, "/oss/picture", params, new OkJsonObjectResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog("正在上传头像");
            }

            @Override
            public void onSuccess(JSONObject jsonObject) {
                mAvatar = jsonObject;
                register();
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
                super.onFail(status, s, throwable);
                cancelProgressDialog();
            }

            @Override
            public void onStop() {
            }
        });
    }


    private void register() {
        User user = new User();
        user.setPassword(getIntent().getStringExtra("password"));
        user.setUsername(getIntent().getStringExtra("username"));
        user.setDeviceId(AppTool.getDeviceId());
        user.setAvatarThumbUrl(mAvatar.getString("picThumbUrl"));
        user.setAvatarMediumUrl(mAvatar.getString("picMediumUrl"));
        user.setAvatarOriginUrl(mAvatar.getString("picOriginUrl"));
        user.setRegisterLon(mLon);
        user.setRegisterLat(mLat);
        user.setLon(mLon);
        user.setLat(mLat);
        user.setNickname(mNicknameV.getText().toString());
        user.setMotto(mMottoV.getText().toString());
        user.setPhone(AppTool.getPhoneNo());
        user.setRegisterTime(System.currentTimeMillis());

        OkRestClient.getInstance().post(this,
                "/user/register",
                user,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在注册");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        if (UserMgr.save(jsonObject)) {
                            Intent intent = new Intent(RegisterInfoActivity.this,
                                    MainActivity.class);
                            startActivity(intent);
                            EventBus.getDefault().post(new UserEvent(UserEvent.LOGIN));
                        }
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
